package com.lucy.management.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtil {
 
    private static final long EXPIRATION_TIME = 3600_000_000L; // 1000 hour 有效期
    private static final String SECRET = "xhdxkzzpyqsh";//  密钥
 
    //解析
    public static Claims parseJWT(String jsonWebToken) {
        return Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                .parseClaimsJws(jsonWebToken).getBody();
    }

 
    //生成
    public static String createJWT(String userId,String schoolId,String userName, String realName,String role) {
        //当前时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT")
                .claim("userId", userId)
                .claim("schoolId", schoolId)
                .claim("userName", userName)
                .claim("realName", realName)
                .claim("role",role)
                .signWith(SignatureAlgorithm.HS256, signingKey);
        //添加Token过期时间
        long expMillis = nowMillis + EXPIRATION_TIME;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
        //生成JWT
        return builder.compact();
    }

 
}